package com.jeff.android.lab;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

/**
 * @author: duff
 * @date: 2019/1/7
 * @since: 1.0.0
 */
public class FragmentDependActivity<T extends Fragment> extends BaseActivity {
    public final static String EXTRA_CLASS = "clazz"; // Fragment 类
    public final static String EXTRA_BUNDLE = "bundle"; // Fragment 携带数据

    private T mFragment;
    private Bundle mBundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_depend);

        handleIntent(getIntent());

        if (mFragment != null) {
            if (mBundle != null)
                mFragment.setArguments(mBundle);

            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, mFragment)
                    .commitAllowingStateLoss();
        }
    }

    private void handleIntent(Intent intent) {
        if (intent != null) {
            Class<T> clazz = (Class<T>) intent.getSerializableExtra(EXTRA_CLASS);
            try {
                if (clazz != null) {
                    mFragment = clazz.newInstance();
                    mBundle = intent.getBundleExtra(EXTRA_BUNDLE);
                }
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}
